/*jslint vars: true, forin: true, sloppy: true */
/*global angular, ocDialog, DialogManager, evalEach */
var evaluate = function (data) {
	if (data === null) {
		return "<hr />";
	}
	if (data.hasOwnProperty('attr')) {
		return '<li><a ' + data.attr + '>' + data.title + '</a></li>';
	}
	if (data.hasOwnProperty('sub')) {
		return '<li class="sub">' + data.title + '<ul>' + evalEach(data.sub) + '</ul></li>';
	}

	return '<li><a>' + data.title + '</a></li>';
}, evalEach = function (raw) {
	return raw.reduce(function (out, item) {
		return out + evaluate(item);
	}, "");
};

ocDialog.directive("ocListMenu", function () {
	return {
		replace: true,
		controller: angular.noop,
		template:
			'<menu class="oc-menu" ng-class="{focus: isFocus}" ng-click="toggleMenu()">' +
				'<li ng-repeat="m in content track by $index" ng-click="">{{m.title}}' +
					'<ul oc-menu-sub="{{$index}}"></ul></li></menu>',
		restrict: 'E',
		scope: {
			content: "="
		},
		link: function (scope, element, attrs) {
			// Transfer the original scope into isolating scope.
			scope.originScope = scope.$parent;

			// Control oc-menu isolation state.
			scope.isFocus = false;
			scope.toggleMenu = function () {
				scope.isFocus = !scope.isFocus;
			};
		}
	};
}).directive("ocMenuSub", function ($compile) {
	return {
		restrict: "A",
		require: '^ocListMenu',
		link: function (scope, element, attrs) {
			// Render the list in sub-menu.
			var subList = scope.content[attrs.ocMenuSub].menu;
			element.append($compile(evalEach(subList))(scope.originScope));
		}
	};
});
